package demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import demo.common.Result;
import demo.entity.User;
import demo.mapper.UserMapper;
import demo.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/user")
public class UserController {
  @Resource
  UserMapper userMapper;

  @PostMapping("/login")
  public Result<?> login(@RequestBody User user) {
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("username", user.getUsername());
    queryWrapper.eq("password", user.getPassword());
    queryWrapper.eq("role", user.getRole());
    User res = userMapper.selectOne(queryWrapper);
    if (res == null) {
      return Result.error("-1", "用户名或密码错误");
    }
    // 生成token
    String token = TokenUtils.genToken(res);
    res.setToken(token);
    return Result.success(res);
  }
  @PostMapping("/register")
  public Result<?> register(@RequestBody User user) {
    User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
    if (res != null) {
      return Result.error("-1", "用户名重复");
    }
    if (user.getPassword() == null) {
      user.setPassword("123456");
    }
    user.setRole(2);
    userMapper.insert(user);
    return Result.success();
  }
}
